using System;
using System.Web.Mvc;
using RMH.DataAccess;
using RMH.Entities;

namespace RMH.Web.Models.Binders
{
    public class RoomBinder : IModelBinder
    {
        private IRoomRepository roomRepository;

        public RoomBinder(IRoomRepository roomRepository)
        {
            this.roomRepository = roomRepository;
        }

        public RoomBinder()
        {
            roomRepository = Container.Resolve<RoomRepository>();
        }

        public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
        {
            var form = controllerContext.HttpContext.Request.Form;

            Room rv = new Room();

            if (!String.IsNullOrEmpty(form["Id"]))
                rv = roomRepository.GetByID(Int32.Parse(form["Id"]));
            int roomNumber = 0;
            if (!String.IsNullOrEmpty(form["RoomNumber"]))
                Int32.TryParse(form["RoomNumber"], out roomNumber);
            rv.RoomNumber = roomNumber;

            DateTime startDate = DateTime.MinValue;
            if (!string.IsNullOrEmpty(form["StartDate"]))
            {
                DateTime.TryParse(form["StartDate"], out startDate);
            }
            rv.StartDate = startDate;

            return rv;
        }
    }
}